package com.openlogic.system.service.impl;

import java.util.List;

import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Tran;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.openlogic.common.core.constants.CacheConstant;
import com.openlogic.common.core.enums.DictEnum;
import com.openlogic.common.core.web.exception.ServiceException;
import com.openlogic.common.redis.service.RedisService;
import com.openlogic.system.domain.SysConfig;
import com.openlogic.system.mapper.SysConfigMapper;
import com.openlogic.system.service.ISysConfigService;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 系统参数配置 服务层实现
 * @author xm
 */
@Component
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    @Inject
    SysConfigMapper sysConfigMapper;

    @Inject
    RedisService redisService;

    /**
     * 根据键名查询参数配置信息
     * @param configKey 参数key
     * @return
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String cacheKey = getCacheKey(configKey);
        String configValue = redisService.getCacheObject(cacheKey);
        if (StrUtil.isNotEmpty(configValue)) {
            return configValue;
        }
        QueryWrapper qw = QueryWrapper.create();
        qw.where(SysConfig::getConfigKey).eq(configKey);
        SysConfig sysConfig = sysConfigMapper.selectOneByQuery(qw);
        if (ObjectUtil.isNotNull(sysConfig)) {
            redisService.setCacheObject(cacheKey, sysConfig.getConfigValue());
            return sysConfig.getConfigValue();
        }
        return StrUtil.EMPTY;
    }

    /**
     * 新增系统参数配置
     * @param sysConfig
     * @return
     */
    @Override
    public int add(SysConfig sysConfig) {
        if (!checkConfigKeyUnique(sysConfig)) {
            throw new ServiceException("参数键名已存在");
        }
        int row = sysConfigMapper.insert(sysConfig);
        if (row > 0) {
            redisService.setCacheObject(getCacheKey(sysConfig.getConfigKey()), sysConfig.getConfigValue());
        }
        return row;
    }

    /**
     * 修改系统参数配置
     * @param sysConfig
     * @return
     */
    @Tran
    @Override
    public int edit(SysConfig sysConfig) {
        if (!checkConfigKeyUnique(sysConfig)) {
            throw new ServiceException("参数键名已存在");
        }
        SysConfig oldConfig = sysConfigMapper.selectOneById(sysConfig.getConfigId());
        // 如果键名都改了，删除旧键名的缓存
        if(!oldConfig.getConfigKey().equals(sysConfig.getConfigKey())) {
            redisService.deleteCacheObject(getCacheKey(oldConfig.getConfigKey()));
        }
        int row = sysConfigMapper.update(sysConfig);
        if (row > 0) {
            redisService.setCacheObject(getCacheKey(sysConfig.getConfigKey()), sysConfig.getConfigValue());
        }
        return row;
    }

    /**
     * 删除系统参数配置
     * @param dictIds
     * @return
     */
    @Override
    public void delete(List<Long> dictIds) {
        List<SysConfig> sysConfigs = sysConfigMapper.selectListByIds(dictIds);
        for (SysConfig sysConfig : sysConfigs) {
            if(DictEnum.COMMON_YES_NO.YES.getValue().equals(sysConfig.getConfigType())) {
                throw new ServiceException("内置参数不能删除");
            }
            sysConfigMapper.deleteById(sysConfig.getConfigId());
            redisService.deleteCacheObject(getCacheKey(sysConfig.getConfigKey()));
        }
    }

    /**
     * 刷新系统参数配置缓存
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> sysConfigs = sysConfigMapper.selectAll();
        redisService.deleteCacheObjectAll(getCacheKey("*"));
        for (SysConfig sysConfig : sysConfigs) {
            redisService.setCacheObject(getCacheKey(sysConfig.getConfigKey()), sysConfig.getConfigValue());
        }
    }

    /**
     * 校验参数键名是否唯一
     * @param sysConfig
     * @return
     */
    private boolean checkConfigKeyUnique(SysConfig sysConfig) {
        long configId = sysConfig.getConfigId() == null ? -1L : sysConfig.getConfigId();
        QueryWrapper qw = QueryWrapper.create();
        qw.and(SysConfig::getConfigKey).eq(sysConfig.getConfigKey());
        qw.limit(1);
        SysConfig sc = sysConfigMapper.selectOneByQuery(qw);
        return ObjectUtil.isNull(sc) || sc.getConfigId() == configId;
    }

    private String getCacheKey(String key) {
        return CacheConstant.SYS_CONFIG_KEY + key;
    }

}
